package com.yksj.healthtalk.ui.doctorstation.active;

import java.util.ArrayList;
import java.util.List;

import org.universalimageloader.core.DefaultConfigurationFactory;
import org.universalimageloader.core.DisplayImageOptions;
import org.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;
//奖品领取
public class LucklyDrawActivity extends BaseFragmentActivity implements OnClickListener {
	
	JSONArray mJsonArray;
	ImageLoader mImageLoader;
	Button prizeButton;
	String activityId;
	String customerId;
	String prizeId;
	String message;
	String prizeName;
	List<View> prizeList = new ArrayList<View>();
	Animation animation = null;
	int prizeIndex = -1;//中奖的索引位置
	private String prizeImgPath;
	private String RECEIVING_FLAG;
	DisplayImageOptions displayImageOptions;
	DisplayImageOptions circularImageOptions;
	
	
	final Handler mHandler = new Handler(){
		int overRounds = 0;//剩下需要旋转的位置索引
		int currenIndex = 0;//当前位置
		int speed = 200;//初始速度
		int rounds = 0;//圈数
		int deceleration = 0;//减速度
		final int maxSpeed = 50;
		final int acceleration = 10;//加速度
		View currentView;
		
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 0://开始
				currenIndex = 0;
				rounds = 0;
				sendEmptyMessage(1);
				speed = 200;
				break;
				
			case 1://运行中
				//圈数到最大了退出
				if(currentView != null){
					currentView.clearAnimation();
				}
				//计算圈数
				if(currenIndex == 9){
					currenIndex = 0;
					rounds++;
					//开始减速度哦
					if(rounds == 3){
						//当前速度减去初始速度，计算减速度是多少
						deceleration = (speed - 200)/(overRounds = (prizeIndex + 9));
						sendEmptyMessageDelayed(2,deceleration);
						return;
					}
				}
				currentView = prizeList.get(currenIndex);
				currentView.startAnimation(animation);
				sendEmptyMessageDelayed(1,speed);
				if(rounds >= 2){
					speed += acceleration;//减速度
				}else{
					speed -= acceleration;//加速度
				}
				currenIndex++;
				break;
			case 2://减速度
				if(overRounds == 0){
					sendEmptyMessageDelayed(3,1000);
					return;
				}
				if(currentView != null){
					currentView.clearAnimation();
				}
				--overRounds;
				++currenIndex;
				if(currenIndex == 9){
					currenIndex = 0;
				}
				currentView = prizeList.get(currenIndex);
				currentView.startAnimation(animation);
				speed += deceleration;//减速度
				sendEmptyMessageDelayed(2,speed);
				break;
			case 3://-1结束
				prizeButton.setClickable(true);
				currenIndex = 0;
				show(message, prizeId);
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.luckly_draw_layout);
		mImageLoader = ImageLoader.getInstance();
		activityId = getIntent().getStringExtra("activityId");
		customerId = getIntent().getStringExtra("customerId");
		
		displayImageOptions = DefaultConfigurationFactory.createPrizeDraw(this);
		circularImageOptions = DefaultConfigurationFactory.createCircularPrizeDraw(this);
		
		
		animation = new AlphaAnimation(0.1f,1.0f);
		animation.setDuration(100);
		
		String content = null;
		if(arg0 != null){
			content = arg0.getString("json");
		}else{
			content = getIntent().getStringExtra("json");
		}
		try{
			mJsonArray = JSON.parseArray(content);
		}catch(JSONException e){
		}
		
		initUI();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("json", mJsonArray.toJSONString());
	}
	
	private void initUI(){
		initTitle();
		setBackBtn("返回",this);
		setTitle(getIntent().getStringExtra("title"));
		prizeButton = (Button)findViewById(R.id.address_btn);
		prizeButton.setOnClickListener(this);
//		mImageLoader.displayImage(uri, imageView);
/*		 {
		        "BIG_PIC_ADDR": "/Dummy_Prize/big_1.jpg",
		        "GOLD_NUM": 100,
		        "PRIZE_DESC": "prize1desc",
		        "PRIZE_ID": 1,
		        "PRIZE_NAME": "prize1",
		        "SMALL_PIC_ADDR": "/Dummy_Prize/small_1.jpg"
		    },
		    */
		for (int i = 0; i < mJsonArray.size(); i++) {
			JSONObject jsonObject = mJsonArray.getJSONObject(i);
			View view = findViewById((R.id.prize1+i));
			view.setTag(jsonObject);
			prizeList.add(view);
			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					JSONObject jsonObject = (JSONObject)v.getTag();
					if(jsonObject.getString("RECEIVING_FLAG").equals("0"))return;
					Intent intent = new Intent(LucklyDrawActivity.this,PrizeIntroduceActivity.class);
					intent.putExtra("json", jsonObject.toJSONString());
					startActivityForResult(intent,100);
				}
			});
			mImageLoader.displayImage(jsonObject.getString("BIG_PIC_ADDR"),(ImageView)view,displayImageOptions);
		}
	/*	findViewById(R.id.prize2);
		findViewById(R.id.prize3);
		findViewById(R.id.prize4);
		findViewById(R.id.prize5);
		findViewById(R.id.prize6);
		findViewById(R.id.prize7);
		findViewById(R.id.prize8);
		findViewById(R.id.prize9);*/
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.prize_frame:
		//case R.id.prize_img://奖品
			RequestParams params = new RequestParams();
			params.put("customerId", customerId);
			params.put("activityId",activityId);
			HttpRestClient.doHttpFindIsGetPrize(params,new JsonsfHttpResponseHandler(this){
				@Override
				public void onSuccess(int statusCode, JSONObject response) {
					int isGet = response.getIntValue("isGet");
					if(isGet != 0){//抽奖 
						JSONObject jsonObject = response.getJSONArray("data").getJSONObject(0);
						//如果抽中是谢谢参与  就直接返回
						if(jsonObject.getString("RECEIVING_FLAG").equals("0")){
							onBackPressed();
						}else{
							Intent intent = new Intent(LucklyDrawActivity.this,PrizeDetailActivity.class);
							intent.putExtra("json",jsonObject.toJSONString());
							startActivity(intent);
						}
					}
				}
			});
			break;
		case R.id.address_btn://抽奖
			/*message = "1111";
			prizeId = "1111";
			show(message, prizeId);*/
			prizeButton.setClickable(false);
			params = new RequestParams();
			params.put("customerId", customerId);
			params.put("activityId", activityId);
			HttpRestClient.doHttpGetPrize(params,new JsonsfHttpResponseHandler(this){
				@Override
				public void onSuccess(int statusCode, JSONObject response) {
					super.onSuccess(statusCode, response);
					if(response.containsKey("error_message")){
						ToastUtil.showToastPanl(response.getString("error_message"));
					}else{
						RECEIVING_FLAG  = response.getString("receiving_flag");
						prizeId = response.getString("prizeId");
						message = response.getString("message");
						if(prizeId == null){
							SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), message);
							return; 
						}
						int size = mJsonArray.size();
						for (int i=0;i<size;i++) {
							JSONObject jsonObject = mJsonArray.getJSONObject(i);
							String prizeid = jsonObject.getString("PRIZE_ID");
							//计算奖品的索引位置
							if(prizeid.equals(prizeId)){
								prizeIndex = i;
								prizeImgPath = jsonObject.getString("BIG_PIC_ADDR");
								prizeName = jsonObject.getString("PRIZE_NAME");
								break;
							}
						}
						mHandler.sendEmptyMessage(0);
					}
				}
				@Override
				public void onFinish() {
					super.onFinish();
					prizeButton.setClickable(true);
				}
			});
			break;
		}
	} 
	
	public void show(String messge,String prizeid){
		View view = findViewById(R.id.prize_frame);
		view.setVisibility(View.VISIBLE);
		view.setOnClickListener(this);
		mImageLoader.displayImage(prizeImgPath,(ImageView)findViewById(R.id.prize_img),circularImageOptions);
		TextView prizeView = (TextView)findViewById(R.id.prize_msg);
		TextView	prize_name = (TextView)findViewById(R.id.prize_name);
		//谢谢参与
		if("0".equals(RECEIVING_FLAG)){
//			prizeView.setVisibility(View.GONE);
			prize_name.setVisibility(View.GONE);
		}else{
			prizeView.setVisibility(View.VISIBLE);
			prize_name.setVisibility(View.VISIBLE);;
		}
		prizeView.setText(prizeName);
		prize_name.setText(messge);
	}

}
